import {getOssConfig,imgFileUpload} from '@/api/other';
import {parseTime} from '@/utils/datetime';

const uniqueId = function()
{
  return Math.random().toString(36).substring(2) +
    Math.random().toString(36).substring(2) +
    (new Date()).getTime().toString(36);
};

/**
 * 上传配置
 * */
const upload = {
  state: {
    client: {},
    ossType: '',
    ossLoaded: false,
    ossConfig: {},
  },
  mutations: {
    SET_CONFIG: (state, payload) => {
      state.ossLoaded = true;
      state.ossType = payload.type;
      state.ossConfig = payload.config;
      state.client = payload.client;
    },
  },
  actions: {
    getOssConfig: ({state, commit}, type) => {
      return new Promise((resolve,reject) => {
        if (type && state.ossLoaded && state.ossType === type)
        {
          resolve();
        }
        else
        {
          getOssConfig(type).then((resp) => {
            let config = resp.data || {};
            
            let client = new window.OSS.Wrapper({
              region: 'oss-cn-hangzhou',
              secure: true,
              accessKeyId: config.accessKeyId,
              accessKeySecret: config.accessKeySecret,
              stsToken: config.securityToken,
              bucket: config.bucket,
              //endpoint: config.endpoint,
            });
            
            let payload = {
              type: type,
              config: config,
              client: client,
            };
            commit('SET_CONFIG', payload);
            resolve();
          },err=>{
            reject(err);
          });
        }
        
      });
    },
    uploadFile: ({state, dispatch, commit}, payload) => {
      //先取配置
      let file = payload.file;
      let type = payload.type;
      let progress = payload.progress;
      
      return dispatch('getOssConfig',type).then(()=>{
        return new Promise((resolve,reject) => {
  
          //文件名：目录+日期+UUID+后缀
          let ext = file.name.substring(file.name.lastIndexOf("."));
          let ymd = parseTime(new Date(),'{y}{m}{d}');
          
          let fileName = type + '/' + ymd + '/' + uniqueId() + ext.toLowerCase();
          
          state.client.multipartUpload(fileName, file, {progress:progress}).then(function (result) {
            console.log(result);
            resolve(result);
          },err=>{
            reject(err);
          });
          
        });
      });
    },
    listFiles:({state,dispatch, commit},payload) =>{
      return dispatch('getOssConfig',payload.type).then(()=>{
        return new Promise((resolve,reject) => {
            state.client.list().then(resp=>{
              resolve(resp)
            }).catch(err=>{
              reject(err);
            });
        });
      });
    },
    uploadFileServer:({state, dispatch, commit},payload) => {
      return new Promise((resolve,reject) =>{
        let type = payload.type;
        let file = payload.file;
        
        let formData = new FormData();
        formData.append('file', file);
        
        imgFileUpload(type, formData).then(resp=>{
          resolve(resp);
        }).catch(err=>{
          reject(err);
        });
      });
    },
  },
  getters: {
  
  }
};

export default upload;
